import {defineStore} from 'pinia'
import {store} from '@/store'
import {login, getInfo, logout} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'

const token = getToken()
const name = 'admin'

export const useUserStore = defineStore({
    id: 'user',
    state: (): { userInfo: {}; roles: any[]; name: string; token: string | undefined } => ({
        token, // token必传值有报错？
        name,
        userInfo: {},
        roles: []
    }),
    getters: {
        getRoles(state) {
            return state.roles
        },
        getName(state) {
            return state.userInfo.nickName
        },
        getUserInfo(state){
            return state.userInfo
        }
    },
    actions: {
        SET_TOKEN(token: string) {
            this.token = token
        },
        // 登入
        Login(data: any) {
            return new Promise<void>((resolve, reject) => {
                login(data.username, data.password, data.code, data.uuid)
                    .then((res: any) => {
                        if (res) {
                            setToken(res.data.token)
                            if (res.data.user.roles.length === 0) {
                                this.roles = ['ROLE_SYSTEM_DEFAULT']
                            } else {
                                this.roles = res.data.user.roles
                            }
                            this.userInfo = res.data.user.user
                            resolve(res)
                        }
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },
        GetInfo() {
            return new Promise<void>((resolve, reject) => {
                getInfo().then(res => {
                    this.userInfo = res.data.user
                    this.roles = res.data.roles
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登出 清空缓存
        LogOut() {
            return new Promise<void>((resolve, reject) => {
                logout().then(() => {
                    this.token = ''
                    removeToken()
                    resolve()
                }).catch(error => {
                    this.token = ''
                    removeToken()
                    reject(error)
                })
            })
        }
    },
})

export function useUserStoreHook() {
    return useUserStore(store)
}
